package com.jiangdg.demo

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.widget.ImageButton
import android.widget.RelativeLayout
import android.widget.SeekBar
import android.widget.TextView
import android.widget.VideoView
import razerdp.basepopup.BasePopupWindow
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale

class VideoPopup(context: Context, private val videoFile: File) : BasePopupWindow(context) {
    private lateinit var videoView: VideoView
    private lateinit var seekBar: SeekBar
    private lateinit var playPauseButton: ImageButton
    private lateinit var currentTimeText: TextView
    private lateinit var totalTimeText: TextView

    private var isPlaying = false
    private var duration = 0

    private val handler = Handler(Looper.getMainLooper())
    private lateinit var updateSeekBarRunnable: Runnable

    init {
        setContentView(R.layout.popup_video)
        setupViews()
        setupVideoView()
        setupControls()
    }

    private fun setupViews() {
        videoView = findViewById(R.id.video_view)
        seekBar = findViewById(R.id.seek_bar)
        playPauseButton = findViewById(R.id.play_pause_button)
        currentTimeText = findViewById(R.id.current_time_text)
        totalTimeText = findViewById(R.id.total_time_text)
        findViewById<RelativeLayout>(R.id.rlClose).setOnClickListener {
            dismiss()
        }
    }

    private fun setupVideoView() {
        videoView.setVideoURI(Uri.fromFile(videoFile))
        videoView.setOnPreparedListener {
            duration = videoView.duration
            seekBar.max = duration
            startUpdatingSeekBar()
        }
    }

    private fun setupControls() {
        playPauseButton.setOnClickListener {
            if (isPlaying) {
                pauseVideo()
            } else {
                startVideo()
            }
        }

        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    videoView.seekTo(progress)
                    updateTimeLabels(progress)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}

            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
    }

    private fun updateTimeLabels(currentPosition: Int) {
        val current = formatTime(currentPosition)
        val total = formatTime(duration)
        currentTimeText.text = current
        totalTimeText.text = total
    }

    private fun formatTime(ms: Int): String {
        val formatter = SimpleDateFormat("mm:ss", Locale.getDefault())
        return formatter.format(ms)
    }
    private fun startUpdatingSeekBar() {
        updateSeekBarRunnable = object : Runnable {
            override fun run() {
                val currentPosition = videoView.currentPosition
                seekBar.progress = currentPosition
                updateTimeLabels(currentPosition)
                handler.postDelayed(this, 1000)
            }
        }
        handler.post(updateSeekBarRunnable)
    }

    private fun startVideo() {
        videoView.start()
        isPlaying = true
        playPauseButton.setImageResource(R.mipmap.ic_pause)
    }

    private fun pauseVideo() {
        videoView.pause()
        isPlaying = false
        playPauseButton.setImageResource(R.mipmap.ic_play)
    }

    override fun onDismiss() {
        super.onDismiss()
        handler.removeCallbacks(updateSeekBarRunnable)
        videoView.stopPlayback()
    }

    override fun onCreateShowAnimator(): Animator {
        return createScaleAnimation(true)
    }

    override fun onCreateDismissAnimator(): Animator {
        return createScaleAnimation(false)
    }

    private fun createScaleAnimation(show: Boolean): Animator {
        val startScale = if (show) 0.5f else 1f
        val endScale = if (show) 1f else 0.5f

        val scaleX = ObjectAnimator.ofFloat(contentView, "scaleX", startScale, endScale)
        val scaleY = ObjectAnimator.ofFloat(contentView, "scaleY", startScale, endScale)

        return AnimatorSet().apply {
            playTogether(scaleX, scaleY)
            duration = 300
        }
    }
}
